<template>
  <view class="container">
    <view
      v-for="(address, index) in addresses"
      :key="index"
      class="address-card"
      :class="{'default-address': address.isDefault}"
    >
      <view class="address-header">
        <!-- 根据路由判断显示按钮 -->
        <button
          v-if="fromHome"
          style="width: 100px;font-size: 15px;height: 30px;"
          @tap="go(index)"
        >
          选择此地址
        </button>
      </view>
      <text class="address">
        {{ address.state }} {{ address.city }} {{ address.addressline2 }} {{ address.addressline1 }}
      </text>
      <view class="contact">
        <text class="name">{{ address.name }}</text>
        <text class="phone">{{ address.phone }}</text>
      </view>
      <view class="buttons">
        <button class="edit-button" @click="() => editAddress(address.addressid)">编辑</button>
        <button class="delete-button" @click="() => deleteAddress(address.addressid)">删除</button>
      </view>
    </view>
    <view class="add-address">
      <button class="add-button" @click="navigateToAddAddress">+ 手动添加</button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import store from '../../../store';
const addresses = ref([]);
const customerId = ref(1); // 假设当前用户ID为1，实际应从登录状态获取
const fromHome = ref(false); // 用于判断是否从 home 页面进入

const app = getApp();
const url = app.globalData.url;

// 获取路由信息
const pages = getCurrentPages();
const currentPage = pages[pages.length - 1];
const fromPage = pages[pages.length - 2]?.route || '';

if (fromPage === 'pages/distribution-home/distribution-home') {
  fromHome.value = true;
} else {
  fromHome.value = false;
}

// 获取地址列表
const fetchAddresses = async (customerId) => {
  const response = await uni.request({
    url: url + 'USER-SERVICE/customerCategory/selectaddresseswx',
    method: 'POST',
    data: { custonmerid: customerId }
  });

  console.log("后端返回的原始数据:", response.data);

  if (response.statusCode === 200) {
    addresses.value = response.data.map((addr) => ({
      addressid: addr.addressid || 0,
      country: addr.country || '未知',
      state: addr.state || '未知',
      city: addr.city || '未知',
      addressline2: addr.addressline2 || '未知',
      addressline1: addr.addressline1 || '未知',
      name: addr.customer?.customerName || '未知',
      phone: addr.customer?.customerPhone || '未知',
      isDefault: addr.isDefault || false
    }));
  } else {
    console.error("加载地址失败，状态码：", response.statusCode);
    uni.showToast({
      title: '加载地址失败',
      icon: 'none'
    });
  }
};

onMounted(() => {
  const customerId = 1; // 假设当前用户ID为1，实际应从登录状态获取
  fetchAddresses(customerId);

  uni.$on('add-address', (address) => {
    addresses.value.push(address);
  });
  uni.$on('update-address', (payload) => {
    const { index, address } = payload;
    addresses.value[index] = address;
  });
});

onBeforeUnmount(() => {
  uni.$off('add-address');
  uni.$off('update-address');
});

const navigateToAddAddress = () => {
  uni.navigateTo({
    url: '/pages/myPage/addAddress/addAddress'
  });
};

// 选择地址
const go = (index) => {
  uni.showModal({
    title: "确认操作",
    content: "确定要选择这个地址吗？",
    showCancel: true,
    success: (res) => {
      if (res.confirm) {
        console.log("用户点击了确定按钮");
        const selectedAddress = addresses.value[index];
        store.dispatch('setAddress', selectedAddress);
        uni.navigateTo({
          url: `/pages/distribution-home/distribution-home`,
        });
      } else if (res.cancel) {
        console.log("用户点击了取消按钮");
      }
    },
  });
};

const editAddress = (addressid) => {
  uni.navigateTo({
    url: `/pages/myPage/reviseAddress/reviseAddress?addressid=${addressid}`
  });
};

const deleteAddress = (addressid) => {
   uni.request({
   url: url+'USER-SERVICE/customerCategory/deladdresseswx',
   method: 'POST',
   data:addressid,
   success(response) {
     if (response.data === 1) {
       uni.showToast({
         title: "删除成功",
         icon: "success"
       });
        addresses.value = addresses.value.filter(addr => addr.addressid !== addressid);
      } else {
        uni.showToast({
          title: "删除失败：" + response.data,
          icon: "none"
        });
      }
    },
    fail(err) {
      console.error("提交失败", err);
      uni.showToast({
        title: "提交失败，请检查网络",
        icon: "none"
      });
    }
  });
};
</script>

<style>
.default-address {
  border-left: 4px solid #007aff; /* 添加左侧边框以突出显示默认地址 */
  padding-left: 10px;
}
.container {
  display: flex;
  flex-direction: column;
  height: calc(100% - 60px);
  background-color: #f5f5f5;
  padding: 10px;
  padding-bottom: 80px;
  overflow-y: auto; /* 添加滚动功能 */
}
uni-page-wrapper {
  background-color: #f5f5f5;
}
.address-card {
  background-color: white;
  width: 87vw;
  margin-bottom: 10px;
  padding: 15px;
  border-radius: 12px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  position: relative;
}

.default-address .default-tag {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: #007aff;
  color: white;
  border-radius: 4px;
  padding: 2px 4px;
  font-size: 12px;
}

.address-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.address {
  font-size: 16px;
  color: #666;
  margin-bottom: 10px;
}

.contact {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.name {
  font-size: 14px;
  color: #333;
}

.phone {
  font-size: 14px;
  color: #007aff;
}

.buttons {
  display: flex;
  justify-content: space-between;
}

.edit-button, .delete-button {
  background-color: transparent;
  border: none;
  color: #007aff;
  font-size: 14px;
  cursor: pointer;
}

.edit-button:hover, .delete-button:hover {
  text-decoration: underline;
}

.add-address {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: white;
  padding: 20px;
  border-top: 1px solid #e5e5e5;
  display: flex;
  justify-content: center;
}

.add-button {
  background-color: #007aff;
  border: none;
  border-radius: 50px;
  padding: 5px 20px;
  font-size: 16px;
  width: 80vw;
  color: white;
  cursor: pointer;
  transition: background-color 0.3s;
}

.add-button:hover {
  background-color: #0056b3;
}
</style>
